package com.teacher.common.config;

import cn.hutool.json.JSONUtil;
import com.teacher.common.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Author: zfm
 * @Date: 2020/4/19 11:44
 */
@RestControllerAdvice
@Slf4j
public class GlobeExceptionHandler {

    public static final String NOAUTH = "不允许访问";

    /**
     * 全局异常处理
     *
     * @param e
     * @return
     */
//    @ExceptionHandler({Exception.class})
    public CommonResult error(Exception e) {
        //log.error(e.getMessage());
        System.out.println(e.getMessage());
        if (e.getMessage().equals(NOAUTH)) {
            return CommonResult.forbidden("无相关权限");
        }
        System.out.println(JSONUtil.toJsonStr(e));
        return CommonResult.failed("服务器繁忙，请稍后再试！");
    }

    /**
     * 方法参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        return CommonResult.failed(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 时间格式参数校验
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public CommonResult handleDateArgument(HttpMessageNotReadableException e) {
        return CommonResult.failed("时间格式错误");
    }

}
